const { body } = require('express-validator');
// const { User } = require('../model')
const md5 = require('../util/md5')
const db = require('../dbbase/db');
//用户验证
const validate = require('../middleware/validator')

exports.register = [
    validate([
        body('user.password').notEmpty().withMessage('密码不能为空！'),
        body('user.usercode').notEmpty().withMessage('员工编号不能为空！'),
    ]),
    validate([
        body('user.usercode').custom( async usercode => {
            const sql = "select * from mov_app_users where usercode=:1";
            const params = [usercode];
            const user = await db.query(sql, params)
            if(user.length != 0){
                return Promise.reject(`员工编号${usercode}已存在`)
            }
        })
    ])
]

exports.login = [
    validate([
        body('user.password').notEmpty().withMessage('密码不能为空！'),
        body('user.usercode').notEmpty().withMessage('员工编号不能为空！')
    ]),
    validate([
        body('user.usercode').custom( async (usercode,req ) => {
            const sql = "select * from mov_app_users where usercode=:1";
            const params = [usercode];
            const user = await db.query(sql, params);
            if(user.length == 0){
                return Promise.reject(`员工编号${usercode}不存在或还未注册`)
            }
            req.user = user;
        })
    ]),
   
]



